package com.ymy.thinking.in.spring.dependency.lookup;

import com.ymy.thinking.in.spring.dependency.lookup.annotation.Fine;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Map;

/**
 * 集合类型依赖查找
 *
 * @author Ringo
 * @date 2021/8/31 13:29
 */
public class DependencyLookupByCollectionTypeDemo {

    public static void main(String[] args) {
        // 创建 IoC 容器
        // ApplicationContext 已经实现了 ListableBeanFactory
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.scan("com.ymy.thinking.in.spring.dependency.lookup.**");

        // 开启 Spring 应用上下文
        applicationContext.refresh();


        // 获取同类型 Bean 名称列表
        String[] beanNamesForType = applicationContext.getBeanNamesForType(String.class);
        System.out.println("获取同类型Bean名称列表: " + Arrays.toString(beanNamesForType));

        // 获取同类型 Bean 实例列表
        Map<String, String> beansOfTypeMap = applicationContext.getBeansOfType(String.class);
        System.out.println("获取同类型 Bean 实例列表: " + beansOfTypeMap);

        // 获得标注注解类型 Bean 名称列表
        String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(Fine.class);
        System.out.println("获得标注注解类型 Bean 名称列表: " + Arrays.toString(beanNamesForAnnotation));

        // 获得标注注解类型 Bean 实例列表
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Fine.class);
        System.out.println("获得标注注解类型 Bean 实例列表: ");
        beansWithAnnotation.forEach((k, v) -> System.out.println(k + "=" + v));

        // 关闭 Spring 应用上下文
        applicationContext.close();

    }

    @Fine
    @Configuration
    public static class Config {

        @Fine
        @Bean
        public String hello() {
            return "hello";
        }

        @Fine
        @Bean
        public String world() {
            return "world";
        }
    }

}
